﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Collections.Generic;

namespace HashFoo.Rest.Common
{
    /// <summary>
    /// A collection of Resource Uris
    /// </summary>
    public class ResourceUriCollection : IResourceUriCollection
    {
        readonly IEnumerable<ResourceUri> _resourceUris;
        readonly IDictionary<Type, string> _lookup; 

        /// <summary>
        /// Creates the collections based on a set of <see cref="ResourceUri"/>s.
        /// </summary>
        /// <param name="resourceUris"></param>
        public ResourceUriCollection(IEnumerable<ResourceUri> resourceUris)
        {
            if (resourceUris == null) throw new ArgumentNullException("resourceUris");

            _resourceUris = resourceUris.Distinct();
            _lookup = _resourceUris.ToDictionary(x => x.ResourceType, x => x.Uri);
        }

        /// <summary>
        /// Get the uri (relative?) for a resource type.
        /// </summary>
        /// <param name="resourceType"></param>
        /// <returns></returns>
        public string GetUri(Type resourceType)
        {
            return _lookup.ContainsKey(resourceType) ? _lookup[resourceType] : null;
        }

        /// <summary>
        /// Get teh uri (relative) for a resource type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public string GetUri<T>()
        {
            return GetUri(typeof(T));
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<ResourceUri> GetEnumerator()
        {
            return _resourceUris.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}